/*
 * Copyright (c) 2009, Jan Pastor. All Rights Reserved.
 */

package sk.jp.commons.ui;

import java.awt.*;
import javax.swing.*;

import sk.jp.commons.tools.Messages;
import sk.jp.commons.utils.StringUtils;

/**
 * Simple question dialog to present text question.
 */
public class QuestionDialog {

    public enum Msg {
        dlgTitle("ui.questiondialog.title"),//
        btnOk("ui.questiondialog.btn.ok"),//OK
        btnCancel("ui.questiondialog.btn.cancel"),//Cancel
        ;
        //----------------------------------------------------------------------
        private String propKey;
        Msg(String propKey) {
            this.propKey = propKey;
        }
        public String getPropKey() {
            return propKey;
        }
        public String value() {
            return Messages.getMessage(propKey);
        }
    }

    //----------------------------------------------------------------------

    private final String title;
    private final String[] options;
    private final String defaultBtnLabel;

    //----------------------------------------------------------------------

    /**
     * Initialize dialog with default properties.
     */
    public QuestionDialog() {
        this(Msg.dlgTitle.value(), new String[]{Msg.btnOk.value(), Msg.btnCancel.value()},
             Msg.btnCancel.value());
    }

    /**
     * Initialize dialog with specified title and close button label.
     * @param title
     * @param defaultButtonLabel
     */
    public QuestionDialog(String title, String[] btnLabels, String defaultButtonLabel) {
        this.title = title;
        this.options = btnLabels;
        this.defaultBtnLabel = defaultButtonLabel;
    }

    //----------------------------------------------------------------------

    /**
     * Presents given text question.
     * @param ownerFrame parent component.
     * @return label of clicked button.
     */
    public String show(Frame ownerFrame, String text){
        text = wrapText(text);
        int r = JOptionPane.showOptionDialog(ownerFrame, text, title,
                                             JOptionPane.OK_CANCEL_OPTION,
                                             JOptionPane.QUESTION_MESSAGE,
                                             null, options, defaultBtnLabel);
        return r!= -1 ? options[r] : defaultBtnLabel;
    }

    //----------------------------------------------------------------------

    private static String wrapText(String text){
        return StringUtils.wrapText(text, 80, StringUtils.SPLIT_EXT, "\n");
    }

}